package com.cx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cx.constant.ProjectStatus;
import com.cx.dto.ProjectDTO;
import com.cx.dto.ProjectPageDTO;
import com.cx.mapper.ProjectMapper;
import com.cx.mapper.TaskMapper;
import com.cx.mapper.UserMapper;
import com.cx.pojo.Project;
import com.cx.pojo.Task;
import com.cx.pojo.User;
import com.cx.service.ProjectService;
import com.cx.service.TaskService;
import com.cx.util.PageResult;
import com.cx.util.ResultUtil;
import com.cx.vo.CommonVO;
import com.cx.vo.ProjectVO;
import com.cx.vo.StatusAndCountVO;
import com.cx.vo.TaskOfProjectVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@RequiredArgsConstructor
public class ProjectServiceImpl implements ProjectService {
    private final ProjectMapper projectMapper;
    private final UserMapper userMapper;
    private final TaskMapper taskMapper;

    @Override
    public ResultUtil add(ProjectDTO projectDTO) {
        int res = projectMapper.add(projectDTO);
        return res > 0 ? ResultUtil.success() : ResultUtil.error("添加项目失败！");
    }

    @Override
    @Transactional
    public ResultUtil<PageResult<ProjectVO>> getProjectList(ProjectPageDTO projectPageDTO) {
        PageHelper.startPage(projectPageDTO.getPage(), projectPageDTO.getPageSize());
        Page<Project> projectPage = projectMapper.pageQuery(projectPageDTO);
        List<Project> result = projectPage.getResult();
        List<ProjectVO> projectVOS = new ArrayList<>(result.size());
        result.forEach(project -> {
            // 根据userId查询项目负责人
            User user = userMapper.selectById(project.getUserId());
            Integer status = project.getStatus();
            ProjectVO projectVO = BeanUtil.copyProperties(project, ProjectVO.class);
            if (Objects.equals(status, ProjectStatus.NOT_TURNED_ON)) {
                projectVO.setStatusToString(ProjectStatus.NOT_TURNED_ON_TOSTRING);
            } else if (Objects.equals(status, ProjectStatus.ADVANCING)) {
                projectVO.setStatusToString(ProjectStatus.ADVANCING_TOSTRING);
            } else if (Objects.equals(status, ProjectStatus.COMPLETED)) {
                projectVO.setStatusToString(ProjectStatus.COMPLETED_TOSTRING);
            } else if (Objects.equals(status, ProjectStatus.TIME_OUT_PROJECT)) {
                projectVO.setStatusToString(ProjectStatus.TIME_OUT_PROJECT_TOSTRING);
            }
            projectVO.setUsername(user.getUsername());
            projectVOS.add(projectVO);
        });
        return ResultUtil.success(new PageResult<>(projectPage.getTotal(), projectVOS));
    }

    @Override
    @Transactional
    public ResultUtil updateStatusById(Integer id) {
        // 根据id查询project
        Project project = projectMapper.selectById(id);
        Integer status = project.getStatus();
        if (Objects.equals(status, ProjectStatus.NOT_TURNED_ON)) {
            // 修改状态为推进中
            projectMapper.updateStatusById(id, ProjectStatus.ADVANCING);
        } else if (Objects.equals(status, ProjectStatus.ADVANCING)) {
            // 修改状态为已完成
            projectMapper.updateStatusById(id, ProjectStatus.COMPLETED);
        } else if (Objects.equals(status, ProjectStatus.TIME_OUT_PROJECT)) {
            // 该项目为超时项目
            return ResultUtil.error("该项目已过规定时间！");
        }
        return ResultUtil.success();
    }

    @Override
    public ResultUtil updateProjectById(ProjectDTO projectDTO) {
        int res = projectMapper.updateProjectById(projectDTO);
        return res > 0 ? ResultUtil.success() : ResultUtil.error("修改失败！");
    }

    @Override
    public ResultUtil<ProjectVO> selectProjectById(Integer id) {
        Project project = projectMapper.selectById(id);
        ProjectVO projectVO = BeanUtil.copyProperties(project, ProjectVO.class);
        return ResultUtil.success(projectVO);
    }

    @Override
    @Transactional
    public ResultUtil deleteProById(Integer id) {
        // 如果该项目下包含任务，则不能删除
        // 根据项目id查找任务
        List<Task> taskList = taskMapper.selectTaskByProjectId(id);
        if (!Objects.isNull(taskList) && !taskList.isEmpty()) {
            return ResultUtil.error("该项目下有任务，不能删除!");
        }
        int res = projectMapper.deleteProById(id);
        return res > 0 ? ResultUtil.success() : ResultUtil.error("删除项目失败！");
    }

    @Override
    public ResultUtil<List<StatusAndCountVO>> selectStatus() {
        List<StatusAndCountVO> projectList = userMapper.selectStatusAnCountVO();
        List<StatusAndCountVO> statusAndCountVOS = new ArrayList<>(projectList.size());
        projectList.forEach(project -> {
            StatusAndCountVO statusAndCountVO = BeanUtil.copyProperties(project, StatusAndCountVO.class);
            if (Objects.equals(project.getStatus(), ProjectStatus.NOT_TURNED_ON)) {
                statusAndCountVO.setName(ProjectStatus.NOT_TURNED_ON_TOSTRING);
            } else if (Objects.equals(project.getStatus(), ProjectStatus.ADVANCING)) {
                statusAndCountVO.setName(ProjectStatus.ADVANCING_TOSTRING);
            } else if (Objects.equals(project.getStatus(), ProjectStatus.COMPLETED)) {
                statusAndCountVO.setName(ProjectStatus.COMPLETED_TOSTRING);
            } else if (Objects.equals(project.getStatus(), ProjectStatus.TIME_OUT_PROJECT)) {
                statusAndCountVO.setName(ProjectStatus.TIME_OUT_PROJECT_TOSTRING);
            }
            statusAndCountVOS.add(statusAndCountVO);
        });
        return ResultUtil.success(statusAndCountVOS);
    }

    @Override
    public ResultUtil<List<TaskOfProjectVO>> selectTaskOfProject() {
        List<TaskOfProjectVO> taskOfProjectVOS = projectMapper.selectTaskOfProject();
        return ResultUtil.success(taskOfProjectVOS);
    }

    @Override
    public ResultUtil<List<CommonVO>> selectUserOfProject() {
        // 获取用户所对应的项目
        List<CommonVO> commonVOS = projectMapper.selectUserOfProject();
        Map<String, List<String>> map = new HashMap<>();
        // 一个用户可能管理多个项目，所以用Map集合存储
        commonVOS.forEach(commonVO -> {
            List<String> list = new ArrayList<>();
            if (!map.containsKey(commonVO.getName())) {
                list.add(commonVO.getPOt());
                map.put(commonVO.getName(), list);
            } else {
                map.put(commonVO.getName(), map.get(commonVO.getName())).add(commonVO.getPOt());
            }
        });
        // 将原commonVOS清空
        commonVOS.clear();
        // 遍历Map集合，将数据存储到commonVOS中
        map.forEach((k, v) -> {
            StringBuilder sb = new StringBuilder();
            v.forEach(v1 -> {
                sb.append(v1).append(" ");
            });
            commonVOS.add(CommonVO.builder().name(k).pOt(sb.toString()).build());
        });
        return ResultUtil.success(commonVOS);
    }
}
